import { createStore } from 'vuex'
const setLocalCartList = (state) => {
  const { cartList } = state
  const cartListString = JSON.stringify(cartList)
  localStorage.cartList = cartListString
}

const getLocaCartList = () => {
  // { shopId: {shopName:'', productList:{ productId: {} }}}
  try {
    return JSON.parse(localStorage.cartList)
  } catch (e) {
    return {}
  }
}
export default createStore({
  state: {
    // 购物车数据 { shopId: {shopName:'', productList:{ productId: {} }}}
    cartList: getLocaCartList(),
    // 去结算数据
    addressList: []
  },
  getters: {},
  mutations: {
    // 购物车加减数据
    changeCartItemInfo(state, payload) {
      const { shopId, productId, productInfo, num } = payload
      // 获取店家信息
      let shopInfo = state.cartList[shopId] || { shopName: '', productList: {} }
      // if (!shopInfo) {
      //   shopInfo = {}
      // }
      // 获取商品信息
      let product = shopInfo.productList[productId]
      if (!product) {
        product = productInfo
        product.count = 0
      }
      product.count = product.count + num
      if (num > 0) {
        product.check = true
      }
      // 边界处理，不允许为负数
      if (product.count < 0) {
        product.count = 0
      }
      // 店家 商品
      shopInfo.productList[productId] = product
      state.cartList[shopId] = shopInfo
      setLocalCartList(state)
    },
    // 添加购物车的商品名称
    changeShopName(state, payload) {
      const { shopId, shopName } = payload
      const shopInfo = state.cartList[shopId] || {
        shopName: '',
        productList: {}
      }
      shopInfo.shopName = shopName
      state.cartList[shopId] = shopInfo
      setLocalCartList(state)
    },
    // 改变选中状态
    changeCartItemChecked(state, payload) {
      const { shopId, productId } = payload
      const product = state.cartList[shopId].productList[productId]
      product.check = !product.check
      setLocalCartList(state)
    },
    // 清空购物车
    cleanCartProducts(state, payload) {
      const { shopId } = payload
      state.cartList[shopId].productList = {}
      setLocalCartList(state)
    },
    // 全选逻辑
    setCartItemsChecked(state, payload) {
      const { shopId } = payload
      const products = state.cartList[shopId].productList
      if (products) {
        for (let key in products) {
          const product = products[key]
          product.check = true
        }
      }
      setLocalCartList(state)
    },
    clearCartData(state, shopId) {
      state.cartList[shopId].productList = {}
    },
    changeAddressList(state, addressList) {
      state.addressList.splice(0, state.addressList.length, ...addressList)
    }
  },
  actions: {},
  modules: {}
})
